package com.bbcare.util;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.bbcare.util.nullCheck.ObjectNull;
import com.bbcare.util.nullCheck.ObjectNullFactory;

public class FieldNotNullCheck {
	
	private static final String PREFIX_GET = "get";
	private static final String PREFIX_IS = "is";
	private static ObjectNullFactory objectNullFactory;

	@SuppressWarnings("static-access")
	public static boolean fieldNotNullValid(Object obj, String[] notNullFieldNames){
		boolean isValid = true;
		if(notNullFieldNames == null || notNullFieldNames.length == 0)
			return isValid;
		
		Method[] methods = obj.getClass().getMethods();
		for(int i=0;i<methods.length;i++){
			Method method = methods[i];
			if(method.getName().substring(0,3).equals(PREFIX_GET) && method.getAnnotation(FieldNotNull.class) != null){
				Class<?> returnType = method.getReturnType();
				ObjectNull objNull = objectNullFactory.createObjectNull(returnType.getName());
				FieldNotNull fieldNotNull = method.getAnnotation(FieldNotNull.class);
				String nestFieldName = isStrInArray(notNullFieldNames, getFieldName(method.getName()));
				if(StringUtils.isNotBlank(nestFieldName)){
					objNull.isNullCheck(method, obj, fieldNotNull, nestFieldName);
				}
			}
		}
		return isValid;
	}
	
	private static String getFieldName(String methodName){
		String fieldName = null;
		if(methodName.substring(0, 3).equals(PREFIX_GET)){
			fieldName = methodName.substring(3);
		} else if(methodName.substring(0, 2).equals(PREFIX_IS)){
			fieldName = methodName.substring(2);
		}
		if(fieldName != null){
			fieldName = fieldName.substring(0, 1).toLowerCase()+fieldName.substring(1);
		}
		return fieldName;
	}
	
	private static String isStrInArray(String[] notNullFieldNames, String fieldName){
//		return Arrays.asList(notNullFieldNames).contains(fieldName);
		Map<String, String> fieldNamesWrapper = handleFieldNames(notNullFieldNames);
		return fieldNamesWrapper.get(fieldName);
	}
	
	/**
	 * 嵌套处理
	 * 例如：{"id","list:{id,name}"}
	 * @param notNullFieldNames
	 */
	private static Map<String, String> handleFieldNames(String[] notNullFieldNames){
		Map<String, String> fieldNamesWrapper = new HashMap<String, String>();
		for (String nestFieldName : notNullFieldNames) {
			nestFieldName = nestFieldName.trim();
			fieldNamesWrapper.put(nestFieldName.indexOf(":") != -1 ? nestFieldName.substring(0, nestFieldName.indexOf(":")) : nestFieldName, nestFieldName);
		}
		return fieldNamesWrapper;
	}
	
}
